package com.myself.model.demo.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;
/**
 * @author Czx
 */
public class ChatClientBootStrap {


    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("messageDecoder", new StringDecoder());
                        socketChannel.pipeline().addLast("messageEncoder", new StringEncoder());
                        socketChannel.pipeline().addLast(new ChatClientHandler());
                    }
                });
        ChannelFuture sync = bootstrap.connect("127.0.0.1", 9999).sync();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            sync.channel().writeAndFlush(s);
        }
        sync.channel().closeFuture().sync();
        eventExecutors.shutdownGracefully();

    }
}
